import mongoose from 'mongoose'

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: [true, '姓名是必填项'],
        trim: true,
        maxlength: [50, '姓名不能超过50个字符']
    },
    email: {
        type: String,
        required: [true, '邮箱是必填项'],
        unique: true,
        trim: true,
        lowercase: true,
        match: [
            /^\w+([.-]?\w+)*@\w+([.-]?\w+)*(\.\w{2,3})+$/,
            '请输入有效的邮箱地址'
        ]
    },
    age: {
        type: Number,
        required: [true, '年龄是必填项'],
        min: [1, '年龄必须大于0'],
        max: [120, '年龄不能超过120']
    }
}, {
    timestamps: true, // 自动添加 createdAt 和 updatedAt 字段
    versionKey: false // 不添加 __v 字段
})

// 创建索引
userSchema.index({ email: 1 })
userSchema.index({ createdAt: -1 })

// 实例方法
userSchema.methods.toJSON = function () {
    const user = this.toObject()
    return user
}

// 静态方法
userSchema.statics.findByEmail = function (email) {
    return this.findOne({ email: email.toLowerCase() })
}

const User = mongoose.model('User', userSchema)

export default User
